package com.dfrz.bookstore.service.impl;

import com.dfrz.bookstore.dao.impl.BookDaoImpl;
import com.dfrz.bookstore.dao.impl.OrderItemDaoImpl;
import com.dfrz.bookstore.entry.Book;
import com.dfrz.bookstore.entry.Order;
import com.dfrz.bookstore.entry.OrderItem;
import com.dfrz.bookstore.service.OrderItemService;

import javax.swing.*;
import java.util.List;

/**
 * 类功能描述:
 *
 * @Author keyan
 * @Date 2021/5/21 9:47
 */
public class OrderItemServiceImpl implements OrderItemService {
    OrderItemDaoImpl orderItemDao = new OrderItemDaoImpl();
    BookServiceImpl bookService = new BookServiceImpl();
    @Override
    public void inertOrderItem(OrderItem orderItem,int num) {
        //不能有重复的订单项
//        List<OrderItem> orderItems = orderItemDao.findObjByObj(orderItem);
//        if (orderItems.size()==0){
            /*计算价格*/
            //TODO
            boolean flag = orderItemDao.insert(orderItem);
            if (flag){
                JOptionPane.showMessageDialog(null,"订单项生成成功");
                /*减少对应的图书库存*/
                Book book = new Book();
                book.setId(orderItem.getBook_id());
                book = bookService.findBookByBook(book).get(0);
                book.setStore(book.getStore()-num);
                bookService.upDataBook(book);
            }else {
                JOptionPane.showMessageDialog(null,"订单项生成失败");
            }
//        }else {
//            JOptionPane.showMessageDialog(null,"订单项存在 无法添加");
//        }


    }

    @Override
    public void delectOrderItemById(int id) {
        OrderItem orderItem = new OrderItem();
        orderItem.setId(id);
        List<OrderItem> orderItemList = orderItemDao.findObjByObj(orderItem);
        if (orderItemList.size()>0){
            //确认是否要删除
            int opt = JOptionPane.showConfirmDialog(null,
                    "请确认你要删除的订单项吗?", "确认信息",
                    JOptionPane.YES_NO_OPTION);
            if (opt == JOptionPane.YES_OPTION) {
                //确认继续操作
                orderItemDao.deleteObjById(id);

            }
        }else {
            JOptionPane.showMessageDialog(null,"删除失败");
        }
    }

    @Override
    public void upDataOrderItem(OrderItem orderItem) {
        boolean flag = orderItemDao.updateByObj(orderItem);
        if (flag){
            System.out.println("更新成功");
            //TODO
//            调用刷新
        }else{
            System.out.println("更新失败");
        }

    }

    @Override
    public List<OrderItem> findObjByObj(OrderItem orderItem) {
        List<OrderItem> orderItems = orderItemDao.findObjByObj(orderItem);
        return orderItems;
    }

    @Override
    public List<OrderItem> findOrderItemByPage(OrderItem orderItem, int pageNum, int pageSize) {
        List<OrderItem> orderItems = orderItemDao.findObjByPage(orderItem, pageNum, pageSize);
        return orderItems;
    }
}
